<template>
  <div class="image-generation-page">
    <van-nav-bar
      title="AI文生图"
      left-arrow
      @click-left="$router.go(-1)"
      class="custom-nav-bar"
    />

    <!-- 介绍区域 -->
    <div class="intro-section">
      <div class="intro-content">
        <div class="intro-text">
          <h3>AI图像生成</h3>
          <p>用文字描述你想要的图片，AI帮你创作独特的艺术作品</p>
        </div>
      </div>
      <div class="intro-examples">
        <div class="example-title">💡 试试这些描述：</div>
        <div class="example-tags">
          <span
            v-for="example in examples"
            :key="example"
            class="example-tag"
            @click="askExample(example)"
          >
            {{ example }}
          </span>
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="chat-container" ref="chatContainer">
      <div v-if="messages.length === 0" class="empty-chat">
        <div class="empty-icon">🎨</div>
        <p>请描述你想要生成的图片</p>
      </div>

      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message-item"
        :class="message.type"
      >
        <div class="message-content">
          <div v-if="message.type === 'user'" class="user-message">
            {{ message.content }}
          </div>
          <div v-else class="ai-message">
            <div v-if="message.imageUrl" class="generated-image">
              <img
                :src="message.imageUrl"
                alt="生成的图片"
                @click="previewImage(message.imageUrl)"
                @error="handleImageError(message, index)"
                @load="handleImageLoad(message)"
              />
              <div class="image-actions">
                <van-button size="small" type="primary" @click="previewImage(message.imageUrl)">
                  预览图片
                </van-button>
                <van-button size="small" @click="downloadImage(message.originalUrl || message.imageUrl)">
                  下载图片
                </van-button>
              </div>
            </div>
            <div v-else-if="message.content" class="text-content">
              {{ message.content }}
            </div>
            <div v-if="message.type === 'ai' && isLoading && index === messages.length - 1" class="loading-indicator">
              <van-loading size="16" />
              <span>AI正在创作中...</span>
            </div>
          </div>
        </div>
        <div class="message-time">
          {{ formatTime(message.timestamp) }}
        </div>
      </div>
    </div>

    <!-- 风格和尺寸选择 -->
    <div class="settings-section">
      <div class="setting-group">
        <label class="setting-label">风格：</label>
        <van-dropdown-menu>
          <van-dropdown-item v-model="selectedStyle" :options="styleOptions" />
        </van-dropdown-menu>
      </div>
      <div class="setting-group">
        <label class="setting-label">尺寸：</label>
        <van-dropdown-menu>
          <van-dropdown-item v-model="selectedSize" :options="sizeOptions" />
        </van-dropdown-menu>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-section">
      <div class="input-container">
        <van-field
          v-model="inputText"
          placeholder="描述你想要的图片，比如：一只可爱的小猫在花园里玩耍"
          type="textarea"
          rows="2"
          @keyup.enter="sendMessage"
          :disabled="isLoading"
        />
        <van-button
          type="primary"
          :loading="isLoading"
          @click="sendMessage"
          :disabled="!inputText.trim()"
        >
          <van-icon name="photo" />
        </van-button>
      </div>


    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { showToast, showImagePreview } from 'vant'
import aiService from '@/services/aiService'

// 响应式数据
const inputText = ref('')
const messages = ref<Array<{
  type: 'user' | 'ai'
  content: string
  imageUrl?: string
  originalUrl?: string
  timestamp: number
}>>([])
const isLoading = ref(false)
const chatContainer = ref<HTMLElement>()

// 风格和尺寸选择
const selectedStyle = ref('realistic')
const selectedSize = ref('512x512')

// 风格选项
const styleOptions = ref([
  { text: '写实风格', value: 'realistic' },
  { text: '卡通风格', value: 'cartoon' },
  { text: '动漫风格', value: 'anime' },
  { text: '油画风格', value: 'oil_painting' },
  { text: '水彩画风格', value: 'watercolor' },
  { text: '素描风格', value: 'sketch' },
  { text: '抽象风格', value: 'abstract' },
  { text: '像素风格', value: 'pixel' }
])

// 尺寸选项
const sizeOptions = ref([
  { text: '512×512 (正方形)', value: '512x512' },
  { text: '768×512 (横版)', value: '768x512' },
  { text: '512×768 (竖版)', value: '512x768' },
  { text: '1024×1024 (高清正方形)', value: '1024x1024' },
  { text: '1024×768 (高清横版)', value: '1024x768' },
  { text: '768×1024 (高清竖版)', value: '768x1024' }
])

// 示例描述
const examples = ref([
  '一只可爱的小猫在花园里',
  '夕阳下的海边风景',
  '科幻城市夜景',
  '梦幻森林中的小屋',
  '宇宙中的星球',
  '古风美女肖像'
])

// 发送消息
const sendMessage = async () => {
  const prompt = inputText.value.trim()
  if (!prompt || isLoading.value) return

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: prompt,
    timestamp: Date.now()
  })

  inputText.value = ''
  isLoading.value = true

  await scrollToBottom()

  // 添加AI消息占位符
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '正在生成图片...',
    timestamp: Date.now()
  })

  try {
    // 调用AI图片生成服务，使用选择的风格和尺寸
    const response = await aiService.imageGeneration(12345, prompt, selectedStyle.value, selectedSize.value)

    console.log('图片生成响应:', response)

    if (response.code === 200 && response.data) {
      // 图片URL在response.data.response中
      const responseText = response.data.response

      console.log('原始响应文本:', responseText)

      if (responseText) {
        // 从响应中提取图片URL
        const imageUrl = extractImageUrlFromMarkdown(responseText)

        console.log('提取的图片URL:', imageUrl)

        if (imageUrl) {
          // 直接使用带签名的阿里云OSS URL
          // 阿里云OSS的签名URL应该可以直接访问
          messages.value[aiMessageIndex] = {
            type: 'ai',
            content: '图片生成完成！',
            imageUrl: imageUrl,
            originalUrl: imageUrl, // 保存原始URL用于下载
            timestamp: Date.now()
          }
        } else {
          // 如果无法提取URL，显示AI的完整原始回复
          messages.value[aiMessageIndex].content = responseText || '图片生成失败，AI未返回有效的图片链接。'
        }
      } else {
        // 显示AI的完整响应内容
        messages.value[aiMessageIndex].content = '图片生成完成，但响应为空。'
      }
    } else {
      console.error('图片生成失败:', response)
      // 显示后端返回的详细错误信息
      let errorMessage = '图片生成失败'
      if (response.message) {
        errorMessage = response.message
      } else if (response.data && response.data.response) {
        // 如果有AI的响应内容，显示给用户
        errorMessage = response.data.response
      }
      messages.value[aiMessageIndex].content = errorMessage
    }

  } catch (error) {
    console.error('图片生成异常:', error)
    messages.value[aiMessageIndex].content = '网络异常，图片生成失败。请检查网络连接后重试。'
  } finally {
    isLoading.value = false
    await scrollToBottom()
  }
}

// 从Markdown文本中提取图片URL
const extractImageUrlFromMarkdown = (text: string): string | null => {
  if (!text) return null

  console.log('正在解析文本:', text)

  // 首先检查文本是否直接就是一个URL
  const trimmedText = text.trim()
  if (trimmedText.startsWith('http://') || trimmedText.startsWith('https://')) {
    console.log('检测到直接URL:', trimmedText)
    return trimmedText
  }

  // 匹配Markdown图片格式: ![alt](url) 或 ![](url)
  const markdownImageRegex = /!\[.*?\]\((https?:\/\/[^\s\)]+)\)/g
  let match = markdownImageRegex.exec(text)

  if (match && match[1]) {
    let url = match[1]
    // 清理URL，移除可能的尾随字符
    url = url.replace(/[)\]"'>]+$/, '')
    console.log('从Markdown格式提取到URL:', url)
    return url
  }

  // 如果没有找到Markdown格式，尝试直接匹配图片URL
  const imageUrlRegex = /(https?:\/\/[^\s\)]+\.(?:png|jpg|jpeg|gif|webp|bmp|svg)[^\s\)]*)/gi
  let urlMatch = imageUrlRegex.exec(text)

  if (urlMatch && urlMatch[1]) {
    let url = urlMatch[1]
    // 清理URL，移除可能的尾随字符
    url = url.replace(/[)\]"'>]+$/, '')
    console.log('从图片URL模式提取到URL:', url)
    return url
  }

  // 尝试匹配AI图片生成服务的URL（DashScope、阿里云OSS等）
  const aiImageRegex = /(https?:\/\/[^\s\)]*(?:dashscope|oss|aliyun|qwen)[^\s\)]*)/gi
  let aiImageMatch = aiImageRegex.exec(text)

  if (aiImageMatch && aiImageMatch[1]) {
    let url = aiImageMatch[1]
    url = url.replace(/[)\]"'>]+$/, '')
    console.log('从AI图片服务提取到URL:', url)
    return url
  }

  // 最后尝试匹配任何以http开头的URL
  const generalUrlRegex = /(https?:\/\/[^\s\)]+)/g
  let generalMatch = generalUrlRegex.exec(text)

  if (generalMatch && generalMatch[1]) {
    let url = generalMatch[1]
    // 清理URL，移除可能的尾随字符
    url = url.replace(/[)\]"'>]+$/, '')
    console.log('从通用模式提取到URL:', url)
    return url
  }

  console.log('未能提取到有效的图片URL，原始文本:', text)
  return null
}

// 点击示例描述
const askExample = (example: string) => {
  inputText.value = example
}



// 预览图片
const previewImage = (imageUrl: string) => {
  showImagePreview([imageUrl])
}

// 图片加载成功
const handleImageLoad = (message: any) => {
  console.log('图片加载成功:', message.imageUrl)
}

// 图片加载失败
const handleImageError = (message: any, index: number) => {
  console.error('图片加载失败:', message.imageUrl)
  showToast('图片显示失败，但已生成成功')

  // 显示友好的错误信息和解决方案
  messages.value[index] = {
    ...message,
    imageUrl: null,
    content: `✅ 图片已成功生成！\n\n❌ 但由于浏览器安全限制无法直接显示\n\n💡 解决方案：\n1. 点击下方链接在新窗口打开\n2. 右键链接选择"图片另存为"\n3. 或者重新生成图片\n\n🔗 图片链接：\n${message.originalUrl || message.imageUrl}`
  }
}

// 下载图片
const downloadImage = (imageUrl: string) => {
  if (!imageUrl) return

  const link = document.createElement('a')
  link.href = imageUrl
  link.download = `ai-generated-${Date.now()}.jpg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  showToast('开始下载图片')
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  messages.value.push({
    type: 'ai',
    content: '你好！我是AI图像生成助手。请描述你想要的图片，我会为你创作独特的艺术作品。',
    timestamp: Date.now()
  })
})
</script>

<style scoped>
.image-generation-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.custom-nav-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.intro-section {
  background: rgba(255, 255, 255, 0.95);
  margin: 16px;
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.intro-content {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.intro-text h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.intro-text p {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.intro-examples {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.example-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.example-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.example-tag {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.example-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.chat-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  max-height: calc(100vh - 300px);
}

.empty-chat {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.8);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.message-item {
  margin-bottom: 16px;
}

.message-item.user {
  text-align: right;
}

.message-content {
  display: inline-block;
  max-width: 80%;
  word-wrap: break-word;
}

.user-message {
  background: rgba(255, 255, 255, 0.95);
  color: #333;
  padding: 12px 16px;
  border-radius: 18px 18px 4px 18px;
  backdrop-filter: blur(10px);
}

.ai-message {
  background: rgba(255, 255, 255, 0.95);
  color: #333;
  padding: 12px 16px;
  border-radius: 18px 18px 18px 4px;
  backdrop-filter: blur(10px);
}

.generated-image {
  text-align: center;
  padding: 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.generated-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: transform 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.generated-image img:hover {
  transform: scale(1.02);
}

.image-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
  justify-content: center;
}

.image-actions .van-button {
  border-radius: 20px;
}

.text-content {
  line-height: 1.5;
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
  margin-top: 8px;
}

.message-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 4px;
}

.message-item.user .message-time {
  text-align: right;
}

.input-section {
  background: rgba(255, 255, 255, 0.95);
  padding: 16px;
  backdrop-filter: blur(10px);
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  margin-bottom: 12px;
}

.input-container .van-field {
  flex: 1;
  background: white;
  border-radius: 12px;
}

.quick-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-actions .van-button {
  border-radius: 16px;
}

/* 风格和尺寸选择器样式 */
.settings-section {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  margin-bottom: 16px;
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.setting-group {
  flex: 1;
  min-width: 140px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.setting-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.setting-group .van-dropdown-menu {
  flex: 1;
}

.setting-group .van-dropdown-menu__bar {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.setting-group .van-dropdown-menu__title {
  font-size: 13px;
  color: #333;
}
</style>
